package controller;

import business.ebi.UserEBI;
import business.factory.BusinessFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

@WebServlet(name = "LoginController",urlPatterns = "/loginServlet")
public class LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("method");
        if (action!=null){
            try {
                Method method =this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
                method.invoke(this,req,resp);
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }else {
            this.doPost(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        UserEBI userEBI = BusinessFactory.getUserEBI();
        try {
            if (userEBI.check(req.getParameter("username"), req.getParameter("password"))) {
                resp.addCookie(new Cookie("username", req.getParameter("username")));
                req.getRequestDispatcher("/CommodityListController").forward(req, resp);
            } else {
                resp.getWriter().write("<script language=javascript>alert('" + "密码错误" + "');window.location='login.html'</script>");
            }
        } catch (SQLException | NullPointerException e) {
            resp.getWriter().write("<script language=javascript>alert('" + "用户名不存在!点击确定前往注册页面" + "');window.location='Register.jsp?state=register'</script>");
        }
    }

    protected void forgetPwd(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/Register.jsp?state=forget").forward(req,resp);
    }
}
